<template>
  <view class="start-index">
    <!-- tab内容区域，页面内根据角色动态渲染 -->
    <view
      v-if="tabberPageLoadFlag[0]"
      :style="{ display: currentIndex === 0 ? '' : 'none' }"
    >
      <console-view :is-onsite="isOnsite" ref="console"></console-view>
    </view>
    <view
      v-if="tabberPageLoadFlag[1]"
      :style="{ display: currentIndex === 1 ? '' : 'none' }"
    >
      <home-view :is-onsite="isOnsite" ref="home"></home-view>
    </view>
    <view
      v-if="tabberPageLoadFlag[2]"
      :style="{ display: currentIndex === 2 ? '' : 'none' }"
    >
      <mine-view :is-onsite="isOnsite" ref="mine"></mine-view>
    </view>

    <!-- 自定义tabbar背景和内容 -->
    <view class="custom-tabbar">
      <image
        src="/static/img/tabbar/tabbarBg.png"
        class="tabbar-bg"
        mode="scaleToFill"
      />
      <view
        class="tabbar-item"
        :class="{ active: currentIndex === 0 }"
        @click="switchTabbar(0)"
      >
        <image
          :src="
            currentIndex === 0
              ? '/static/img/tabbar/work-active.png'
              : '/static/img/tabbar/work.png'
          "
          class="tabbar-icon"
        />
        <text class="tabbar-text">处理</text>
      </view>
      <view
        class="tabbar-item bulge"
        :class="{ active: currentIndex === 1 }"
        @click="switchTabbar(1)"
      >
        <image src="/static/img/tabbar/bulge-bg.svg" class="bulge-btn-img" />
      </view>
      <view
        class="tabbar-item"
        :class="{ active: currentIndex === 2 }"
        @click="switchTabbar(2)"
      >
        <image
          :src="
            currentIndex === 2
              ? '/static/img/tabbar/mine-active.png'
              : '/static/img/tabbar/mine.png'
          "
          class="tabbar-icon"
        />
        <text class="tabbar-text">我的</text>
      </view>
    </view>
    <view class="float-btn" @click="goTest">
      <text>Test</text>
    </view>
    <view class="float-btn test2-btn" @click="goTest2">
      <text>Test2</text>
    </view>
    <view class="float-btn test3-btn" @click="goTest3">
      <text>Test3</text>
    </view>
  </view>
</template>

<script setup>
import { ref, computed, onMounted, onUnmounted } from 'vue';
import { onLoad, onUnload } from '@dcloudio/uni-app';
import HomeView from '@/pages/homePages/homeView.vue';
import ConsoleView from '@/pages/consolePages/consoleView.vue';
import MineView from '@/pages/minePages/mineView.vue';
import { mygo } from '@/utils/useNavigator';
import { useGlobalStore } from '@/store/app';
import { useNotificationStore } from '@/store/notification';
import { useAlarmStore } from '@/store/alarm';
import config from '@/utils/config';
import { createRequest } from '@/utils/request';

const currentIndex = ref(1); // 默认选中首页
const tabberPageLoadFlag = ref([]);
const store = useGlobalStore();
const notificationStore = useNotificationStore();
const alarmStore = useAlarmStore();
const userRole = computed(() => store.getRole());
const isOnsite = computed(() => userRole.value === 'onsite');

// 消息类型枚举 - 只保留实时推送类型
const MessageType = {
  NOTIFICATION: 'notification',  // 实时通知推送
  ALARM: 'alarm',               // 实时告警推送
  HEARTBEAT: 'heartbeat',       // 心跳
  AUTH: 'auth'                  // 认证
};

// tabbar配置（如需区分角色可在此处动态调整）
const tabbarList = [
  {
    title: '操作',
    activeIcon: '/static/img/tabbar/work-active.png',
    inactiveIcon: '/static/img/tabbar/work.png',
  },
  {
    title: '首页',
    activeIcon: '/static/img/tabbar/home-active.png',
    inactiveIcon: '/static/img/tabbar/home.png',
    isSpecial: true,
  },
  {
    title: '我的',
    activeIcon: '/static/img/tabbar/mine-active.png',
    inactiveIcon: '/static/img/tabbar/mine.png',
  },
];

// WebSocket连接管理
import { useWebSocket } from '@/utils/websocket';

const { 
  connect, 
  disconnect, 
  onMessage,
  clearAllMessageHandlers
} = useWebSocket();

// 初始化WebSocket连接
const initWebSocket = async () => {
  try {
    const token = store.userInfo?.token || '';
    
    // 构建带token的WebSocket URL
    const wsUrl = `${config.websocket.url}?token=${token}`;
    
    const success = await connect(wsUrl);
    if (success) {
      console.log('WebSocket连接成功');
      // 注册全局消息处理器
      registerGlobalMessageHandlers();
    }
  } catch (error) {
    console.error('WebSocket初始化失败:', error);
  }
};

// 注册全局消息处理器
const registerGlobalMessageHandlers = () => {
  // 实时通知推送处理
  onMessage(MessageType.NOTIFICATION, (data) => {
    console.log('收到实时通知推送:', data);
    notificationStore.addNotification(data);
  });
  
  // 实时告警推送处理
  onMessage(MessageType.ALARM, (data) => {
    console.log('收到实时告警推送:', data);
    alarmStore.handleRealtimeAlarm(data);
  });
  
  console.log('消息处理器注册完成');
};

// 加载初始数据 - 使用HTTP请求获取批量数据
const loadInitialData = async () => {
  try {
    // 并行加载通知和告警数据
    const [notifications, alarms] = await Promise.all([
      loadNotifications(),
      loadAlarms()
    ]);
    
    console.log('初始数据加载完成');
  } catch (error) {
    console.error('加载初始数据失败:', error);
  }
};

// 获取通知列表
const loadNotifications = async () => {
  try {
    
  } catch (error) {
    console.error('加载通知列表失败:', error);
  }
};

// 获取告警列表
const loadAlarms = async () => {
  try {
    const result = await createRequest('/alert/getRangeAlertList');
    if (result.code === 200 && result.data) {
      alarmStore.setAlarmList(result.data);
      console.log('告警列表:', result.data);
    }
  } catch (error) {
    console.error('获取告警列表失败:', error);
  }
};

const switchTabbar = index => {
  _switchTabbarPage(index);
};

const _switchTabbarPage = index => {
  const selectPageFlag = tabberPageLoadFlag.value[index];
  if (selectPageFlag === undefined) {
    return;
  }
  if (selectPageFlag === false) {
    tabberPageLoadFlag.value[index] = true;
  }
  currentIndex.value = index;
};

const goTest = () => {
  mygo('/pages/test');
};

const goTest2 = () => {
  mygo('/pages/test2');
};

const goTest3 = () => {
  mygo('/pages/test3');
};



onLoad(async (options) => {
  const index = Number(options.index || 1);
  tabberPageLoadFlag.value = tabbarList.map((item, tabbar_index) => {
    return index === tabbar_index;
  });
  switchTabbar(index);
  
  // 初始化WebSocket连接（只用于实时推送）
  initWebSocket();
  
  // 使用HTTP请求获取批量数据
  await loadInitialData();
});

onUnload(() => {
  disconnect();
  clearAllMessageHandlers();
});

</script>

<style lang="scss" scoped>
.start-index {
  min-height: 100vh;
  background-color: #f8f8f8;
  padding-bottom: 100rpx;
  box-sizing: border-box;
}
.custom-tabbar {
  bottom: 0;
  left: 0;
  right: 0;
  position: fixed;
  width: 100vw;
}
.custom-tabbar {
  height: 142rpx;
  z-index: 101;
  display: flex;
  align-items: flex-end;
  justify-content: space-between;
  background: transparent;
  pointer-events: auto;
  padding: 0;
}
.tabbar-bg {
  position: fixed;
  width: 100vw;
  height: 142rpx;
  bottom: 0;
  left: 0;
  right: 0;
  bottom: 5rpx;
  z-index: 100;
  transform: scale(1.2);
}
.tabbar-item {
  flex: 1;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: flex-end;
  height: 142rpx;
  position: relative;
  z-index: 102;
  // 增加内容上移
  padding-bottom: -4rpx;
}

.tabbar-icon {
  width: 56rpx;
  height: 56rpx;
  margin-bottom: 8rpx;
  display: block;
}
.tabbar-text {
  font-size: 22rpx;
  color: #b3d6f7;
  margin-bottom: 6rpx;
}
.tabbar-item.active .tabbar-text {
  color: #4fd2ff;
  font-weight: bold;
}
.bulge {
  margin-bottom: 20rpx; // 让中间按钮更凸起
  width: 120rpx;
  height: 120rpx;
  z-index: 104;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: flex-end;
  transform: scale(1.1);
}
.bulge-btn-img {
  width: 120rpx;
  height: 120rpx;
  display: block;
}
.bulge-btn-text {
  position: absolute;
  left: 50%;
  bottom: 12rpx;
  transform: translateX(-50%);
  color: #fff;
  font-size: 28rpx;
  font-weight: bold;
  letter-spacing: 2rpx;
  z-index: 105;
  text-shadow: 0 2rpx 8rpx #1e3c72, 0 2rpx 8rpx #000;
  pointer-events: none;
}
.float-btn {
  position: fixed;
  right: 40rpx;
  bottom: 180rpx;
  z-index: 999;
  width: 100rpx;
  height: 100rpx;
  background: linear-gradient(135deg, #1ec8e1 0%, #1ed6b7 100%);
  color: #fff;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 32rpx;
  box-shadow: 0 8rpx 24rpx rgba(30, 200, 225, 0.18);
  font-weight: bold;
  letter-spacing: 2rpx;
}

.test2-btn {
  bottom: 300rpx;
  background: linear-gradient(135deg, #ff6b6b 0%, #ee5a52 100%);
  box-shadow: 0 8rpx 24rpx rgba(255, 107, 107, 0.18);
}

.test3-btn {
  bottom: 420rpx;
  background: linear-gradient(135deg, #9c27b0 0%, #673ab7 100%);
  box-shadow: 0 8rpx 24rpx rgba(156, 39, 176, 0.18);
}


</style>
